package jp.co.piratealliance.pirateAllianceWeb.web.action.goods;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;

import jp.co.piratealliance.pirateAllianceWeb.common.base.BaseAction;
import jp.co.piratealliance.pirateAllianceWeb.def.Constants;
import jp.co.piratealliance.pirateAllianceWeb.def.SystemConf;
import jp.co.piratealliance.pirateAllianceWeb.dto.com.UserInfoDto;
import jp.co.piratealliance.pirateAllianceWeb.dto.goods.GoodsInfoDto;
import jp.co.piratealliance.pirateAllianceWeb.dto.goods.ResourceTypeInfoDto;
import jp.co.piratealliance.pirateAllianceWeb.helper.CommonHelper;
import jp.co.piratealliance.pirateAllianceWeb.service.goods.GoodsService;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;


/**
 * copyright pirate alliance team 2014
 *
 * @author lw
 */

public class GoodsManagerWebAction extends BaseAction {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private GoodsService goodsService;

	private List<GoodsInfoDto> goodsList;
	
	/**日本語商品詳細＊＊*/
	//商品名
	private String goodsName1;
	//価額
	private String goodsPrice1;
	//説明
	private String description1;
	//状態
	private String status1="1";
	
    private File file1;

    private String file1ContentType;

    private String file1FileName;
    private String file1FileUrl;
	
	/**簡体中文商品詳細＊＊*/
	//商品名
	private String goodsName2;
	//価額
	private String goodsPrice2;
	//説明
	private String description2;
	//状態
	private String status2 ="1" ;
	
    private File file2;

    private String file2ContentType;

    private String file2FileName;
    private String file2FileUrl;
    
    
	/**English商品詳細＊＊*/
	//商品名
	private String goodsName3;
	//価額
	private String goodsPrice3;
	//説明
	private String description3;
	//状態
	private String status3 = "1";
	
    private File file3;

    private String file3ContentType;

    private String file3FileName;
    private String file3FileUrl;
    
	private List<ResourceTypeInfoDto> resourceList;
    
    private String selectedAreaID;
    
	/**goodsIdForModify＊＊*/
	private String goodsIdForModify="";
	private String languageIdForModify="";
	
	private String selectedResourceTypes;
	
	private Map<String, String> payTypeMap;
	
	private int pay_type_id;
	
	private String addGoodsFlag;
	
	private String selectLanguageFlag;
	//add by hmh
	private String mapFlag;
	
	public String getMapFlag() {
		return mapFlag;
	}

	public void setMapFlag(String mapFlag) {
		this.mapFlag = mapFlag;
	}

	//商品管理页面初期化
	public String goodsManagerInit()
	{
		//TODO USERID
		//String userId="0000000000000001";
		//String userId="testabc";
		UserInfoDto userDto=(UserInfoDto) ActionContext.getContext().getSession().get("user");
		if(userDto!=null){
		this.goodsList = this.goodsService.getGoodsListByUserId(userDto.getUser_id());
		resourceList = goodsService.getResourceTypeListInfo();
		//初始化:支付方法下拉框
		payTypeMap=goodsService.getPayTypeMap();
		return SUCCESS;
		}
		return INPUT;
	}
	
	//新增商品
	public String modifyGoodsInfoInit()
	{
		this.goodsManagerInit();
		
		
		String goodsId = ServletActionContext.getRequest().getParameter("goodsId");
		String languageId = ServletActionContext.getRequest().getParameter("languageId");
		goodsIdForModify = goodsId;
		languageIdForModify =  languageId;		
		List<GoodsInfoDto> eidtGoodsList = this.goodsService.getGoodsListByGoodsId(goodsId);
		this.setGoodsInfoForModify(eidtGoodsList);	
		resourceList = goodsService.getResourceTypeListInfo();	
		selectedResourceTypes = goodsService.getGoodsResourceTypes(goodsId);
		mapFlag="1";
		return SUCCESS;
	}
	
	private void saveFile(File file,String fileContentType, String fileName, String langName,String goodsId) throws IOException{
		
       if(file==null)
        {
    	   return ;
        }
		
		// 以服务器的文件保存地址和原文件名建立上传文件输出流
		//String  rootPath = ServletActionContext.getServletContext().getRealPath("/images/goodsPhotos/");
       String  rootPath = SystemConf.getImageRootDir() + Constants.PATH_SEPEARTOR + Constants.GOODS_IMAGE_PATH + Constants.PATH_SEPEARTOR;
		File savePath = new File(rootPath+Constants.PATH_SEPEARTOR+ goodsId+Constants.PATH_SEPEARTOR+langName);
		if(!savePath.exists()){
			savePath.mkdirs();
		}
		
	  //String path = ServletActionContext.getServletContext().getRealPath("/images/goodsPhotos/"+goodsId+"/"+langName);
		String path = SystemConf.getImageRootDir()+Constants.PATH_SEPEARTOR + Constants.GOODS_IMAGE_PATH + Constants.PATH_SEPEARTOR+goodsId+Constants.PATH_SEPEARTOR+langName;
        InputStream is=new FileInputStream(file);

        OutputStream os=new FileOutputStream(new File(path,fileName));

        byte[] buf=new byte[1024];

        int length=0;

        while((length=is.read(buf))>0)

        {
            os.write(buf, 0, length);
        }
        is.close();
        os.close();
         
	}
	
	public void validateSaveGoodsInfo(){
		this.goodsManagerInit();
		
		if(StringUtils.isEmpty(goodsName1) && StringUtils.isEmpty(goodsPrice1) &&
				StringUtils.isEmpty(description1) && StringUtils.isEmpty(file1FileName) &&
				StringUtils.isEmpty(goodsName2) && StringUtils.isEmpty(goodsPrice2) &&
				StringUtils.isEmpty(description2) && StringUtils.isEmpty(file2FileName) &&
				StringUtils.isEmpty(goodsName3) && StringUtils.isEmpty(goodsPrice3) &&
				StringUtils.isEmpty(description3) && StringUtils.isEmpty(file3FileName)) {
			Locale locale = Locale.getDefault();
			ResourceBundle rb = ResourceBundle.getBundle("message", locale);
			this.addActionError(rb.getString("validation0013"));
			return;
		}
		
		if(!(StringUtils.isEmpty(goodsName1) && StringUtils.isEmpty(goodsPrice1) &&
				StringUtils.isEmpty(description1) && StringUtils.isEmpty(file1FileName))) {
			Locale locale = new Locale("ja", "JP");
			ResourceBundle rb = ResourceBundle.getBundle("message", locale);

			if(StringUtils.isEmpty(goodsName1)) {
				this.addFieldError("goodsName1", MessageFormat.format(rb.getString("validation0001"), rb.getString("label_goodsName")));
			}
			
			if(StringUtils.isEmpty(goodsPrice1)) {
				this.addFieldError("goodsPrice1", MessageFormat.format(rb.getString("validation0001"), rb.getString("label_goodsPrice")));
			}
			
			if(StringUtils.isEmpty(description1)) {
				this.addFieldError("description1", MessageFormat.format(rb.getString("validation0001"), rb.getString("label_goodsDescription")));
			}
			
			if(StringUtils.isEmpty(file1FileName) && StringUtils.isEmpty(file1FileUrl)) {
				this.addFieldError("file1FileName", rb.getString("label_noPicture"));
			}
			
//			if(goodsPrice1!=null && !goodsPrice1.isEmpty())
//			{
//				try{
//					Float.parseFloat(goodsPrice1);
//				}catch(Exception e){
//					this.addFieldError("goodsPrice1", "请输入正确金额");
//				}
//				
//			}
		}
		
		if(!(StringUtils.isEmpty(goodsName2) && StringUtils.isEmpty(goodsPrice2) &&
				StringUtils.isEmpty(description2) && StringUtils.isEmpty(file2FileName))) {
			Locale locale = new Locale("zh", "CN");
			ResourceBundle rb = ResourceBundle.getBundle("message", locale);
		
			if(StringUtils.isEmpty(goodsName2)) {
				this.addFieldError("goodsName2", MessageFormat.format(rb.getString("validation0001"), rb.getString("label_goodsName")));
			}
			
			if(StringUtils.isEmpty(goodsPrice2)) {
				this.addFieldError("goodsPrice2", MessageFormat.format(rb.getString("validation0001"), rb.getString("label_goodsPrice")));
			}
			
			if(StringUtils.isEmpty(description2)) {
				this.addFieldError("description2", MessageFormat.format(rb.getString("validation0001"), rb.getString("label_goodsDescription")));
			}
			
			if(StringUtils.isEmpty(file2FileName) && StringUtils.isEmpty(file2FileUrl)) {
				this.addFieldError("file2FileName", rb.getString("label_noPicture"));
			}
			
//			if(goodsPrice2!=null && !goodsPrice2.isEmpty())
//			{
//				try{
//					Float.parseFloat(goodsPrice2);
//				}catch(Exception e){
//					this.addFieldError("goodsPrice2", "请输入正确金额");
//				}
//				
//			}
		}
		
		if(!(StringUtils.isEmpty(goodsName3) && StringUtils.isEmpty(goodsPrice3) &&
				StringUtils.isEmpty(description3) && StringUtils.isEmpty(file3FileName))) {
			Locale locale = new Locale("en", "US");
			ResourceBundle rb = ResourceBundle.getBundle("message", locale);
			
			if(StringUtils.isEmpty(goodsName3)) {
				this.addFieldError("goodsName3", MessageFormat.format(rb.getString("validation0001"), rb.getString("label_goodsName")));
			}
			
			if(StringUtils.isEmpty(goodsPrice3)) {
				this.addFieldError("goodsPrice3", MessageFormat.format(rb.getString("validation0001"), rb.getString("label_goodsPrice")));
			}
			
			if(StringUtils.isEmpty(description3)) {
				this.addFieldError("description3", MessageFormat.format(rb.getString("validation0001"), rb.getString("label_goodsDescription")));
			}
			
			if(StringUtils.isEmpty(file3FileName) && StringUtils.isEmpty(file3FileUrl)) {
				this.addFieldError("file3FileName", rb.getString("label_noPicture"));
			}
			
//			if(goodsPrice3!=null && !goodsPrice3.isEmpty())
//			{
//				try{
//					Float.parseFloat(goodsPrice3);
//				}catch(Exception e){
//					this.addFieldError("goodsPrice3", "请输入正确金额");
//				}
//				
//			}
		}
		
	}
	
	//登録商品
	public String saveGoodsInfo() throws IOException
	{
		  
	
		String userId="";
		UserInfoDto userDto=(UserInfoDto) ActionContext.getContext().getSession().get("user");
		if(userDto!=null){
			userId = userDto.getUser_id();
		}
		
		String goodsId="";
		
		if("".equals(goodsIdForModify)){
			goodsId = CommonHelper.getSequence(Constants.TB_GOODS);
			this.goodsIdForModify=goodsId;
			List<GoodsInfoDto> goodsInfoListForSave = this.setGoodsLanguageInfoList();
            this.goodsService.saveGoodsInfo(goodsInfoListForSave,userId,selectedAreaID,selectedResourceTypes,pay_type_id,goodsId);
		}else{
			List<GoodsInfoDto> goodsInfoListForSave = this.setGoodsLanguageInfoList();
			this.goodsService.updateGoodsInfo(goodsInfoListForSave,goodsIdForModify,selectedAreaID,selectedResourceTypes,pay_type_id);
			goodsId = goodsIdForModify;
		}
		
		this.saveFile(file1,file1ContentType, file1FileName,Constants.LANGUAGE_JA_PATH,goodsId );
		this.saveFile(file2,file2ContentType, file2FileName,Constants.LANGUAGE_CN_PATH,goodsId );
		this.saveFile(file3,file3ContentType, file3FileName,Constants.LANGUAGE_EN_PATH,goodsId );
		
		addGoodsFlag = "0";
		return SUCCESS;
	}
	
	private List<GoodsInfoDto> setGoodsLanguageInfoList(){
		List<GoodsInfoDto> goodsLanguageInfoList= new ArrayList<GoodsInfoDto>();
		//日本語商品詳細
		GoodsInfoDto goodsInfo1 = new GoodsInfoDto();
		goodsInfo1.setGoods_id(goodsIdForModify);
		goodsInfo1.setLanguage_id(Constants.LANGUAGE_JA_PATH);
		goodsInfo1.setName(goodsName1);
		
		String userId="";
		UserInfoDto userDto=(UserInfoDto) ActionContext.getContext().getSession().get("user");
		if(userDto!=null){
			userId = userDto.getUser_id();
		}
		
		goodsInfo1.setUser_id(userId);
		goodsInfo1.setArea_id(selectedAreaID);
		if(goodsPrice1!=null && !goodsPrice1.isEmpty())
		{
			BigDecimal price1 = new BigDecimal(goodsPrice1);
			goodsInfo1.setPrice(price1);
			goodsInfo1.setCurrency_unit_id(2);
		}
		goodsInfo1.setDescriptionx(description1);
		if(status1!=null && !status1.isEmpty())
		{
			goodsInfo1.setStatus(Integer.parseInt(status1));
		}
		if(file1!=null && file1FileName!=null && !file1FileName.isEmpty()){
			goodsInfo1.setGoods_img(Constants.GOODS_IMAGE_PATH + Constants.PATH_SEPEARTOR+goodsIdForModify+Constants.PATH_SEPEARTOR+Constants.LANGUAGE_JA_PATH+Constants.PATH_SEPEARTOR+file1FileName);
		}
		//簡体中文商品詳細
		GoodsInfoDto goodsInfo2 = new GoodsInfoDto();
		goodsInfo2.setGoods_id(goodsIdForModify);
		goodsInfo2.setLanguage_id(Constants.LANGUAGE_CN_PATH);
		goodsInfo2.setName(goodsName2);
		goodsInfo2.setUser_id(userId);
		goodsInfo2.setArea_id(selectedAreaID);
		if(goodsPrice2!=null && !goodsPrice2.isEmpty())
		{
			BigDecimal price2 = new BigDecimal(goodsPrice2);
			goodsInfo2.setPrice(price2);
			goodsInfo2.setCurrency_unit_id(1);
		}
		goodsInfo2.setDescriptionx(description2);
		if(status2!=null && !status2.isEmpty())
		{
			goodsInfo2.setStatus(Integer.parseInt(status2));
		}
		if(file2!=null && file2FileName!=null && !file2FileName.isEmpty()){
			goodsInfo2.setGoods_img(Constants.GOODS_IMAGE_PATH + Constants.PATH_SEPEARTOR+goodsIdForModify+Constants.PATH_SEPEARTOR+Constants.LANGUAGE_CN_PATH+Constants.PATH_SEPEARTOR+file2FileName);
		}
		//English商品詳細
		GoodsInfoDto goodsInfo3 = new GoodsInfoDto();
		goodsInfo3.setGoods_id(goodsIdForModify);
		goodsInfo3.setLanguage_id(Constants.LANGUAGE_EN_PATH);
		goodsInfo3.setName(goodsName3);
		goodsInfo3.setUser_id(userId);
		goodsInfo3.setArea_id(selectedAreaID);
		if(goodsPrice3!=null && !goodsPrice3.isEmpty())
		{
			BigDecimal price3 = new BigDecimal(goodsPrice3);
			goodsInfo3.setPrice(price3);
			goodsInfo3.setCurrency_unit_id(0);
		}
		goodsInfo3.setDescriptionx(description3);
		if(status3!=null && !status3.isEmpty())
		{
			goodsInfo3.setStatus(Integer.parseInt(status3));
		}
		if(file3!=null && file3FileName!=null && !file3FileName.isEmpty()){
			goodsInfo3.setGoods_img(Constants.GOODS_IMAGE_PATH + Constants.PATH_SEPEARTOR+goodsIdForModify+Constants.PATH_SEPEARTOR+Constants.LANGUAGE_EN_PATH+Constants.PATH_SEPEARTOR+file3FileName);
		}
		
		
		if(goodsInfo1.getName()!=null && !goodsInfo1.getName().isEmpty()){
			goodsLanguageInfoList.add(goodsInfo1);
		}
		if(goodsInfo2.getName()!=null && !goodsInfo2.getName().isEmpty()){
			goodsLanguageInfoList.add(goodsInfo2);
		}
		if(goodsInfo3.getName()!=null && !goodsInfo3.getName().isEmpty()){
			goodsLanguageInfoList.add(goodsInfo3);
		}
		return 	goodsLanguageInfoList;
	}
	
	
	private void setGoodsInfoForModify(List<GoodsInfoDto> goodsInfoList){
		for(GoodsInfoDto goodsInfo : goodsInfoList){
			String languageId = goodsInfo.getLanguage_id();
			String goods_img_name=goodsInfo.getGoods_img().substring(goodsInfo.getGoods_img().lastIndexOf(Constants.PATH_SEPEARTOR)+1);
			selectedAreaID = goodsInfo.getArea_id();
			if(goodsInfo.getPay_type_id()==null){
				pay_type_id = 0;
			}else{
				pay_type_id = goodsInfo.getPay_type_id();
			}
			
			if("ja".equals(languageId)){
				//日本語商品詳細
				goodsName1 = goodsInfo.getName();
				goodsPrice1 = String.valueOf(goodsInfo.getPrice());
				description1 = goodsInfo.getDescriptionx();
				status1 = String.valueOf(goodsInfo.getStatus());
				//file1FileName = goodsInfo.getGoods_img();
				file1FileName=goods_img_name;
				file1FileUrl=goodsInfo.getGoods_img();
			}else if("zh-Hans".equals(languageId)){
				//簡体中文商品詳細
				goodsName2 = goodsInfo.getName();
				goodsPrice2 = String.valueOf(goodsInfo.getPrice());
				description2 = goodsInfo.getDescriptionx();
				status2 = String.valueOf(goodsInfo.getStatus());
				//file2FileName = goodsInfo.getGoods_img();
				file2FileName=goods_img_name;
				file2FileUrl=goodsInfo.getGoods_img();
			}else if("en".equals(languageId)){
				//English商品詳細
				goodsName3 = goodsInfo.getName();
				goodsPrice3 = String.valueOf(goodsInfo.getPrice());
				description3 = goodsInfo.getDescriptionx();
				status3 = String.valueOf(goodsInfo.getStatus());
				//file3FileName = goodsInfo.getGoods_img();
				file3FileName=goods_img_name;
				file3FileUrl=goodsInfo.getGoods_img();
			}
		}
	}
	public String getFile1FileUrl() {
		return file1FileUrl;
	}

	public void setFile1FileUrl(String file1FileUrl) {
		this.file1FileUrl = file1FileUrl;
	}

	public String getFile2FileUrl() {
		return file2FileUrl;
	}

	public void setFile2FileUrl(String file2FileUrl) {
		this.file2FileUrl = file2FileUrl;
	}

	public String getFile3FileUrl() {
		return file3FileUrl;
	}

	public void setFile3FileUrl(String file3FileUrl) {
		this.file3FileUrl = file3FileUrl;
	}

	//更新商品
	public String updateGoods()
	{
		
		return SUCCESS;
	}

	/**
	 * @return the goodsService
	 */
	public GoodsService getGoodsService() {
		return goodsService;
	}

	/**
	 * @param goodsService the goodsService to set
	 */
	public void setGoodsService(GoodsService goodsService) {
		this.goodsService = goodsService;
	}

	public List<GoodsInfoDto> getGoodsList() {
		return goodsList;
	}

	public void setGoodsList(List<GoodsInfoDto> goodsList) {
		this.goodsList = goodsList;
	}

	public String getGoodsName1() {
		return goodsName1;
	}

	public void setGoodsName1(String goodsName1) {
		this.goodsName1 = goodsName1;
	}

	public String getGoodsPrice1() {
		return goodsPrice1;
	}

	public void setGoodsPrice1(String goodsPrice1) {
		this.goodsPrice1 = goodsPrice1;
	}

	public String getDescription1() {
		return description1;
	}

	public void setDescription1(String description1) {
		this.description1 = description1;
	}

	public String getStatus1() {
		return status1;
	}

	public void setStatus1(String status1) {
		this.status1 = status1;
	}

	public String getGoodsName2() {
		return goodsName2;
	}

	public void setGoodsName2(String goodsName2) {
		this.goodsName2 = goodsName2;
	}

	public String getGoodsPrice2() {
		return goodsPrice2;
	}

	public void setGoodsPrice2(String goodsPrice2) {
		this.goodsPrice2 = goodsPrice2;
	}

	public String getDescription2() {
		return description2;
	}

	public void setDescription2(String description2) {
		this.description2 = description2;
	}

	public String getStatus2() {
		return status2;
	}

	public void setStatus2(String status2) {
		this.status2 = status2;
	}

	public String getGoodsName3() {
		return goodsName3;
	}

	public void setGoodsName3(String goodsName3) {
		this.goodsName3 = goodsName3;
	}

	public String getGoodsPrice3() {
		return goodsPrice3;
	}

	public void setGoodsPrice3(String goodsPrice3) {
		this.goodsPrice3 = goodsPrice3;
	}

	public String getDescription3() {
		return description3;
	}

	public void setDescription3(String description3) {
		this.description3 = description3;
	}

	public String getStatus3() {
		return status3;
	}

	public void setStatus3(String status3) {
		this.status3 = status3;
	}

	public String getGoodsIdForModify() {
		return goodsIdForModify;
	}

	public void setGoodsIdForModify(String goodsIdForModify) {
		this.goodsIdForModify = goodsIdForModify;
	}

	public File getFile1() {
		return file1;
	}

	public void setFile1(File file1) {
		this.file1 = file1;
	}

	public File getFile2() {
		return file2;
	}
	
	public void setFile2(File file2) {
		this.file2 = file2;
	}

	public File getFile3() {
		return file3;
	}

	public void setFile3(File file3) {
		this.file3 = file3;
	}

	public String getFile1ContentType() {
		return file1ContentType;
	}

	public void setFile1ContentType(String file1ContentType) {
		this.file1ContentType = file1ContentType;
	}

	public String getFile1FileName() {
		return file1FileName;
	}

	public void setFile1FileName(String file1FileName) {
		this.file1FileName = file1FileName;
	}

	public String getFile2ContentType() {
		return file2ContentType;
	}

	public void setFile2ContentType(String file2ContentType) {
		this.file2ContentType = file2ContentType;
	}

	public String getFile2FileName() {
		return file2FileName;
	}

	public void setFile2FileName(String file2FileName) {
		this.file2FileName = file2FileName;
	}

	public String getFile3ContentType() {
		return file3ContentType;
	}

	public void setFile3ContentType(String file3ContentType) {
		this.file3ContentType = file3ContentType;
	}

	public String getFile3FileName() {
		return file3FileName;
	}

	public void setFile3FileName(String file3FileName) {
		this.file3FileName = file3FileName;
	}

	public String getLanguageIdForModify() {
		return languageIdForModify;
	}

	public void setLanguageIdForModify(String languageIdForModify) {
		this.languageIdForModify = languageIdForModify;
	}

	public String getSelectedAreaID() {
		return selectedAreaID;
	}

	public void setSelectedAreaID(String selectedAreaID) {
		this.selectedAreaID = selectedAreaID;
	}

	public List<ResourceTypeInfoDto> getResourceList() {
		return resourceList;
	}

	public void setResourceList(List<ResourceTypeInfoDto> resourceList) {
		this.resourceList = resourceList;
	}

	public String getSelectedResourceTypes() {
		return selectedResourceTypes;
	}

	public void setSelectedResourceTypes(String selectedResourceTypes) {
		this.selectedResourceTypes = selectedResourceTypes;
	}

	public Map<String, String> getPayTypeMap() {
		return payTypeMap;
	}

	public void setPayTypeMap(Map<String, String> payTypeMap) {
		this.payTypeMap = payTypeMap;
	}

	public int getPay_type_id() {
		return pay_type_id;
	}

	public void setPay_type_id(int pay_type_id) {
		this.pay_type_id = pay_type_id;
	}
	
	public String getAddGoodsFlag() {
		return addGoodsFlag;
	}

	public void setAddGoodsFlag(String addGoodsFlag) {
		this.addGoodsFlag = addGoodsFlag;
	}

	public String getSelectLanguageFlag() {
		return selectLanguageFlag;
	}

	public void setSelectLanguageFlag(String selectLanguageFlag) {
		this.selectLanguageFlag = selectLanguageFlag;
	}
}
